package com.calabar.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.calabar.entity.DataPutEntity;
import com.calabar.put.IDataPut;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p/>
 * <li>Description: 插入数据控制器</li>
 * <li>@author: zijian.wu</li>
 * <li>Date: 2018/4/20 14:56</li>
 */
@RestController
public class PutController {
    /**
     * 日志记录
     */
    private static final Logger LOGGER = LogManager.getLogger(PutController.class);
    /**
     * 插入数据接口对象
     */
    @Autowired
    private IDataPut dataPut;


    /**
     * 插入数据控制方法GET
     *
     * @param json 数据json字符串
     * @throws Exception 参数异常
     */
    @RequestMapping(value = "/api/put", method = RequestMethod.GET, consumes = "application/json")
    String dataPutGetAction(@RequestBody String json) throws Exception {

        //起始时间
        long putStartTime=System.currentTimeMillis();

        //参数验证
        PutParamsValidate.putParamsValidate(json);

        //转为json对象
        List<DataPutEntity> dataList = JSONArray.parseArray(json, DataPutEntity.class);

        //插入数据
        dataPut.put(dataList);

        LOGGER.info("put in "+(System.currentTimeMillis()-putStartTime)+" ms");

        Map<String,Object> response=new HashMap<>();
        response.put("status",200);
        response.put("message","put success");

        return JSON.toJSONString(response);

    }

    /**
     * 插入数据控制方法Post
     *
     * @param json 数据json字符串
     * @throws Exception 参数异常
     */
    @RequestMapping(value = "/api/put", method = RequestMethod.POST, consumes = "application/json")
    String dataPutPostAction(@RequestBody String json) throws Exception {
        return dataPutGetAction(json);
    }
}
